<?php

require_once ROOT_PATH . 'admin/models/ServiceActivityModel.php';
require_once ROOT_PATH . 'admin/models/ServiceAddressModel.php';
$allow_suffix = array('gif', 'jpg', 'png', 'jpeg', 'bmp', 'swf');

class ServiceActivityController {

  public function __construct() {
    $this->activityModel = new ServiceActivityModel();
    $this->addressModel = new ServiceAddressModel();
  }

  public function showList() {
    admin_priv('topic_manage');
    
    $sort_by = empty($_REQUEST['sort_by']) ? 'topic_id' : trim($_REQUEST['sort_by']);
    $sort_order = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
    $record_count = $this->activityModel->getCountActivityList();
    $filter = page_and_size(array('record_count' => $record_count));
        
    $activityList = $this->activityModel->getActivityList($filter['page_size'], $filter['start'], $sort_by, $sort_order);   
    /* PagerHead 数据*/
    $GLOBALS['smarty']->assign('ur_here', '活动网点管理');
    
    /* 分页数据 */
    $pageData = array(
        'filter' => $filter,
        'record_count' => $record_count,
        'page_count' => $filter['page_count'],
    );
    $GLOBALS['smarty']->assign($pageData);
    
    /* 活动列表 */
    $GLOBALS['smarty']->assign('topic_list', $activityList);    

    $sortFlag = sort_flag(array('sort_by' => $sort_by, 'sort_order' => $sort_order));    
    $GLOBALS['smarty']->assign($sortFlag['tag'], $sortFlag['img']);

    assign_query_info();
    $GLOBALS['smarty']->assign('action_link', array('text' => '添加活动网点', 'href' => 'service_activity.php?act=add'));
    $GLOBALS['smarty']->display('service/service_activity_list.htm');
  }

  public function add() {
    admin_priv('topic_manage');

    $isadd = $_REQUEST['act'] == 'add';
    $GLOBALS['smarty']->assign('isadd', $isadd);


    include_once(ROOT_PATH . 'includes/fckeditor/fckeditor.php'); // 包含 html editor 类文件

    $GLOBALS['smarty']->assign('ur_here', '活动点管理');
    $GLOBALS['smarty']->assign('action_link', $this->activityModel->list_link($isadd));

    $GLOBALS['smarty']->assign('cat_list',$this->addressModel->article_cat_list(0, 0, true, 0));

    $GLOBALS['smarty']->assign('cfg_lang', $GLOBALS['_CFG']['lang']);

    $topic = array('title' => '', 'topic_type' => 0, 'url' => 'http://');
    $GLOBALS['smarty']->assign('topic', $topic);

    create_html_editor('topic_intro');
    $GLOBALS['smarty']->assign('act', "insert");

    $GLOBALS['smarty']->display('service/service_activity_add.htm');
  }

  public function insert() {
    admin_priv('topic_manage');

    $is_insert = $_REQUEST['act'] == 'insert';
    $topic_id = empty($_POST['topic_id']) ? 0 : intval($_POST['topic_id']);
    $topic_type = empty($_POST['topic_type']) ? 0 : intval($_POST['topic_type']);

    switch ($topic_type) {
      case '0':
      case '1':

        // 主图上传
        if ($_FILES['topic_img']['name'] && $_FILES['topic_img']['size'] > 0) {
          /* 检查文件合法性 */
          if (!get_file_suffix($_FILES['topic_img']['name'], $GLOBALS['allow_suffix'])) {
            sys_msg($GLOBALS['_LANG']['invalid_type']);
          }

          /* 处理 */
          $name = date('Ymd');
          for ($i = 0; $i < 6; $i++) {
            $name .= chr(mt_rand(97, 122));
          }
          $name .= '.' . end(explode('.', $_FILES['topic_img']['name']));
          $target = ROOT_PATH . DATA_DIR . '/service_activity/' . $name;

          if (move_upload_file($_FILES['topic_img']['tmp_name'], $target)) {
            $topic_img = DATA_DIR . '/service_activity/' . $name;
          }
        } else if (!empty($_REQUEST['url'])) {
          /* 来自互联网图片 不可以是服务器地址 */
          if (strstr($_REQUEST['url'], 'http') && !strstr($_REQUEST['url'], $_SERVER['SERVER_NAME'])) {
            /* 取互联网图片至本地 */
            $topic_img = get_url_image($_REQUEST['url']);
          } else {
            sys_msg($GLOBALS['_LANG']['web_url_no']);
          }
        }
        unset($name, $target);

        $topic_img = empty($topic_img) ? $_POST['img_url'] : $topic_img;
        $htmls = '';

        break;

      case '2':

        $htmls = $_POST['htmls'];

        $topic_img = '';

        break;
    }

    // 标题图上传
    if ($_FILES['title_pic']['name'] && $_FILES['title_pic']['size'] > 0) {
      /* 检查文件合法性 */
      if (!get_file_suffix($_FILES['title_pic']['name'], $GLOBALS['allow_suffix'])) {
        sys_msg($GLOBALS['_LANG']['invalid_type']);
      }

      /* 处理 */
      $name = date('Ymd');
      for ($i = 0; $i < 6; $i++) {
        $name .= chr(mt_rand(97, 122));
      }
      $name .= '.' . end(explode('.', $_FILES['title_pic']['name']));
      $target = ROOT_PATH . DATA_DIR . '/service_activity/' . $name;

      if (move_upload_file($_FILES['title_pic']['tmp_name'], $target)) {
        $title_pic = DATA_DIR . '/service_activity/' . $name;
      }
    } else if (!empty($_REQUEST['title_url'])) {
      /* 来自互联网图片 不可以是服务器地址 */
      if (strstr($_REQUEST['title_url'], 'http') && !strstr($_REQUEST['title_url'], $_SERVER['SERVER_NAME'])) {
        /* 取互联网图片至本地 */
        $title_pic = get_url_image($_REQUEST['title_url']);
      } else {
        sys_msg($GLOBALS['_LANG']['web_url_no']);
      }
    }
    unset($name, $target);

    $title_pic = empty($title_pic) ? $_POST['title_img_url'] : $title_pic;

    require(ROOT_PATH . 'includes/cls_json.php');

    $start_time = local_strtotime($_POST['start_time']);
    $end_time = local_strtotime($_POST['end_time']);

    $json = new JSON;
    $tmp_data = $json->decode($_POST['topic_data']);
    file_put_contents('debug.txt', print_r($tmp_data,true));
    $data = serialize($tmp_data);
    $base_style = $_POST['base_style'];
    $keywords = $_POST['keywords'];
    $description = $_POST['description'];

    if ($is_insert) {
      $sql = "INSERT INTO " . $GLOBALS['ecs']->table('service_activity') . " (title,start_time,end_time,data,intro,template,css,topic_img,title_pic,base_style, htmls,keywords,description)" .
              "VALUES ('$_POST[topic_name]','$start_time','$end_time','$data','$_POST[topic_intro]','$_POST[topic_template_file]','$_POST[topic_css]', '$topic_img', '$title_pic', '$base_style', '$htmls','$keywords','$description')";
    } else {
      $sql = "UPDATE " . $GLOBALS['ecs']->table('service_activity') .
              "SET title='$_POST[topic_name]',start_time='$start_time',end_time='$end_time',data='$data',intro='$_POST[topic_intro]',template='$_POST[topic_template_file]',css='$_POST[topic_css]', topic_img='$topic_img', title_pic='$title_pic', base_style='$base_style', htmls='$htmls', keywords='$keywords', description='$description'" .
              " WHERE topic_id='$topic_id' LIMIT 1";
    }

    $GLOBALS['db']->query($sql);

    clear_cache_files();

    $links[] = array('href' => 'service_activity.php', 'text' => '返回列表');
    sys_msg($GLOBALS['_LANG']['succed'], 0, $links);
  }

  public function query() {
    $sort_by = empty($_REQUEST['sort_by']) ? 'topic_id' : trim($_REQUEST['sort_by']);
    $sort_order = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);    
        
    $record_count = $this->activityModel->getCountActivityList();
    $filter = page_and_size(array('record_count' => $record_count));    
    /* 分页数据 */
    $pageData = array(
        'filter' => $filter,
        'record_count' => $record_count,
        'page_count' => $filter['page_count'],
    );
    $GLOBALS['smarty']->assign($pageData);   
    
    /* 活动列表*/
    $activityList = $this->activityModel->getActivityList($filter['page_size'], $filter['start'], $sort_by, $sort_order);   
    $GLOBALS['smarty']->assign('topic_list', $activityList);    
    /* 排序标记 */   
    $sortFlag = sort_flag(array('sort_by' => $sort_by, 'sort_order' => $sort_order));    
    $GLOBALS['smarty']->assign($sortFlag['tag'], $sortFlag['img']);    

    $tpl = 'service/activity_list.htm';
    make_json_result($GLOBALS['smarty']->fetch($tpl), '', array('filter' => $filter, 'page_count' => $filter['page_count']));
  }

  public function edit() {
    admin_priv('topic_manage');

    $isadd = $_REQUEST['act'] == 'add';
    $GLOBALS['smarty']->assign('isadd', $isadd);
    $topic_id = empty($_REQUEST['topic_id']) ? 0 : intval($_REQUEST['topic_id']);

    include_once(ROOT_PATH . 'includes/fckeditor/fckeditor.php'); // 包含 html editor 类文件

    $GLOBALS['smarty']->assign('ur_here', '活动点管理');
    $GLOBALS['smarty']->assign('action_link', $this->activityModel->list_link($isadd));

    $GLOBALS['smarty']->assign('cat_list', $this->addressModel->article_cat_list(0, 0, true, 0));

    $GLOBALS['smarty']->assign('cfg_lang', $GLOBALS['_CFG']['lang']);


    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('service_activity') . " WHERE topic_id = '$topic_id'";
    $topic = $GLOBALS['db']->getRow($sql);
    $topic['start_time'] = local_date('Y-m-d', $topic['start_time']);
    $topic['end_time'] = local_date('Y-m-d', $topic['end_time']);

    create_html_editor('topic_intro', $topic['intro']);

    require(ROOT_PATH . 'includes/cls_json.php');

    $json = new JSON;
    $topic['data'] = addcslashes($topic['data'], "'");
    $topic['data'] = $json->encode(@unserialize($topic['data']));
    $topic['data'] = addcslashes($topic['data'], "'");

    if (empty($topic['topic_img']) && empty($topic['htmls'])) {
      $topic['topic_type'] = 0;
    } elseif ($topic['htmls'] != '') {
      $topic['topic_type'] = 2;
    } elseif (preg_match('/.swf$/i', $topic['topic_img'])) {
      $topic['topic_type'] = 1;
    } else {
      $topic['topic_type'] = '';
    }

    $GLOBALS['smarty']->assign('topic', $topic);
    $GLOBALS['smarty']->assign('act', "update");

    $GLOBALS['smarty']->display('service/service_activity_edit.htm');
  }

  public function update() {
    admin_priv('topic_manage');

    $is_insert = $_REQUEST['act'] == 'insert';
    $topic_id = empty($_POST['topic_id']) ? 0 : intval($_POST['topic_id']);
    $topic_type = empty($_POST['topic_type']) ? 0 : intval($_POST['topic_type']);

    switch ($topic_type) {
      case '0':
      case '1':

        // 主图上传
        if ($_FILES['topic_img']['name'] && $_FILES['topic_img']['size'] > 0) {
          /* 检查文件合法性 */
          if (!get_file_suffix($_FILES['topic_img']['name'], $allow_suffix)) {
            sys_msg($_LANG['invalid_type']);
          }

          /* 处理 */
          $name = date('Ymd');
          for ($i = 0; $i < 6; $i++) {
            $name .= chr(mt_rand(97, 122));
          }
          $name .= '.' . end(explode('.', $_FILES['topic_img']['name']));
          $target = ROOT_PATH . DATA_DIR . '/afficheimg/' . $name;

          if (move_upload_file($_FILES['topic_img']['tmp_name'], $target)) {
            $topic_img = DATA_DIR . '/afficheimg/' . $name;
          }
        } else if (!empty($_REQUEST['url'])) {
          /* 来自互联网图片 不可以是服务器地址 */
          if (strstr($_REQUEST['url'], 'http') && !strstr($_REQUEST['url'], $_SERVER['SERVER_NAME'])) {
            /* 取互联网图片至本地 */
            $topic_img = get_url_image($_REQUEST['url']);
          } else {
            sys_msg($_LANG['web_url_no']);
          }
        }
        unset($name, $target);

        $topic_img = empty($topic_img) ? $_POST['img_url'] : $topic_img;
        $htmls = '';

        break;

      case '2':

        $htmls = $_POST['htmls'];

        $topic_img = '';

        break;
    }

    // 标题图上传
    if ($_FILES['title_pic']['name'] && $_FILES['title_pic']['size'] > 0) {
      /* 检查文件合法性 */
      if (!get_file_suffix($_FILES['title_pic']['name'], $allow_suffix)) {
        sys_msg($_LANG['invalid_type']);
      }

      /* 处理 */
      $name = date('Ymd');
      for ($i = 0; $i < 6; $i++) {
        $name .= chr(mt_rand(97, 122));
      }
      $name .= '.' . end(explode('.', $_FILES['title_pic']['name']));
      $target = ROOT_PATH . DATA_DIR . '/service_activity/' . $name;

      if (move_upload_file($_FILES['title_pic']['tmp_name'], $target)) {
        $title_pic = DATA_DIR . '/service_activity/' . $name;
      }
    } else if (!empty($_REQUEST['title_url'])) {
      /* 来自互联网图片 不可以是服务器地址 */
      if (strstr($_REQUEST['title_url'], 'http') && !strstr($_REQUEST['title_url'], $_SERVER['SERVER_NAME'])) {
        /* 取互联网图片至本地 */
        $title_pic = get_url_image($_REQUEST['title_url']);
      } else {
        sys_msg($_LANG['web_url_no']);
      }
    }
    unset($name, $target);

    $title_pic = empty($title_pic) ? $_POST['title_img_url'] : $title_pic;

    require(ROOT_PATH . 'includes/cls_json.php');

    $start_time = local_strtotime($_POST['start_time']);
    $end_time = local_strtotime($_POST['end_time']);

    $json = new JSON;
    $tmp_data = $json->decode($_POST['topic_data']);
    $data = serialize($tmp_data);
    $base_style = $_POST['base_style'];
    $keywords = $_POST['keywords'];
    $description = $_POST['description'];


    $sql = "UPDATE " . $GLOBALS['ecs']->table('service_activity') .
            "SET title='$_POST[topic_name]',start_time='$start_time',end_time='$end_time',data='$data',intro='$_POST[topic_intro]',template='$_POST[topic_template_file]',css='$_POST[topic_css]', topic_img='$topic_img', title_pic='$title_pic', base_style='$base_style', htmls='$htmls', keywords='$keywords', description='$description'" .
            " WHERE topic_id='$topic_id' LIMIT 1";

    $GLOBALS['db']->query($sql);

    clear_cache_files();

    $links[] = array('href' => 'service_activity.php', 'text' => '返回列表');
    sys_msg('更新成功', 0, $links);
  }

  public function delete() {

    admin_priv('topic_manage');

    $sql = "DELETE FROM " . $GLOBALS['ecs']->table('service_activity') . " WHERE ";

    if (!empty($_POST['checkboxs'])) {
      $sql .= db_create_in($_POST['checkboxs'], 'topic_id');
    } elseif (!empty($_GET['id'])) {
      $_GET['id'] = intval($_GET['id']);
      $sql .= "topic_id = '$_GET[id]'";
    } else {
      exit;
    }

    $GLOBALS['db']->query($sql);

    clear_cache_files();

    if (!empty($_REQUEST['is_ajax'])) {
      $url = 'service_activity.php?act=query&' . str_replace('act=delete', '', $_SERVER['QUERY_STRING']);
      ecs_header("Location: $url\n");
      exit;
    }

    $links[] = array('href' => 'service_activity.php', 'text' => '返回列表');
    sys_msg('成功删除', 0, $links);
  }
  
  public function getAddressList() {

    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    $filters = $json->decode($_GET['JSON']);

    $filters->keyword = json_str_iconv($filters->keyword);
    $cat_id_sql = empty($filters->cat_id) ? '' : ' and cat_id = ' . $filters->cat_id;
    /* 取得数据 */
    $sql = 'SELECT * ' .
            'FROM ' . $GLOBALS['ecs']->table('service_address') . " WHERE 1 = 1 $cat_id_sql" .
            " AND (title LIKE '%" . mysql_like_quote($filters->keyword) . "%') " .
            'LIMIT 50';

    $arr = $GLOBALS['db']->getAll($sql);

    $opt = array();

    foreach ($arr AS $key => $val) {
      $opt[] = array('value' => $val['article_id'],
          'text' => $val['title']);
    }

    make_json_result($opt);
  }

}
